<?php

namespace app\admin\model\shop;

use think\Model;
use think\Db;
use traits\model\SoftDelete;


class Order extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'shop_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
        'finished_time_text',
        'order_state_text',
        'flag_text',
        'room_text',
        'author_status_text'
    ];


    public function getStatusName()
    {

      return [

            0=>"已拍下",
            //1=>"已通过",
            1=>"未审核",
            2=>"已审核",
            3=>"已上传",
            4=>"已复审",
            5=>"已付款",
            6=>"已下单",
            7=>"待发货",
            8=>"待好评",
            9=>"已发货",
            10=>"已好评",
            11=>"待追评",
            12=>"已追评",
            13=>"已完成"
      ];

    }



    public function getOrderStateList()
    {
        return ['1' => __('Order_state 1'),'2' => __('Order_state 2'),'3' => __('Order_state 3')];
    }

    public function getFlagList()
    {
        return ['1' => __('Flag 1'),'2' => __('Flag 2')];
    }

    public function getRoomList()
    {
        return ['1' => __('Room 1'),'2' => __('Room 2')];
    }

    public function getAuthorStatusList()
    {
        return ['0' => __('Author_status 0'),'1' => __('Author_status 1'),'2' => __('Author_status 2')];
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }




    public function getFinishedTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['finished_time']) ? $data['finished_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOrderStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_state']) ? $data['order_state'] : '');
        $list = $this->getOrderStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getFlagTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['flag']) ? $data['flag'] : '');
        $list = $this->getFlagList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getRoomTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['room']) ? $data['room'] : '');
        $list = $this->getRoomList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getAuthorStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['author_status']) ? $data['author_status'] : '');
        $list = $this->getAuthorStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }



    protected function setFinishedTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }


    public function task(){
        return $this->belongsTo("Task","task_id","task_id");
    }


    public function user(){
        return $this->belongsTo("app\common\model\User","uid","uid");
    }

    public function admin(){
        return $this->belongsTo("app\admin\model\Admin","author","id");
    }

    public function business(){
        return $this->belongsTo("app\admin\model\Admin","shop_admin_id","id");
    }

    public function orderImage(){
        return $this->belongsTo("app\common\model\order\Image","order_id","order_id");
    }

    public function praise(){
        return $this->belongsTo("app\common\model\order\Praise","order_id","order_id");
    }

    public function review(){
        return $this->belongsTo("app\common\model\order\Review","order_id","order_id");
    }


    public function shop(){
        return $this->belongsTo("app\admin\model\Shop","shop_id","shop_id");
    }

    /**
     * 审核,驳回:status:1,3,6,10,12(可审核)
     *
     *  order_id : 订单id
     *
     *  获取任务类型每个任务类型跳转审核的方式不一样
     *
     *  result:1  审核通过
     *
     *  result:2  驳回
     *
     */
    public function examReject($order_id,$status,$result){

        $order_info     = $this->with("task,shop")->where("order_id",$order_id)->find();
        $praise         = $order_info["task"]->is_good_evalute;//是否是好评1：是，2：否
        $review         = $order_info["task"]->is_review;//是否追评
        $deliver        = $order_info["task"]->is_need_send;//是否发货
        $admin_info = session("admin");//总后台用户
        $admin_id = $admin_info["id"];//总后台id
        $task_type_info = "";//任务信息
        if($order_info["task_type"]==1){
            $task_type_info = "精刷单";
        }elseif($order_info["task_type"]==2){
            $task_type_info = "隔日单";
        }elseif($order_info["task_type"]==3){
            $task_type_info = "流量单";
        }
        switch ($status){
//            case 0://待拍单的操作
//                if($result==1){
//                    $this->save(["status"=>1,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);
//                    $uid = $order_info["uid"];
//                    $openid = Db::name("wx_users")->where("uid",$uid)->value("openid");
//                    $content = [
//                        $task_type_info,$order_info["goods_sno"],$order_info["shop_name"],$order_info["shop"]->mobile
//                    ];
//                    $msg = [
//                        "condition"=>11,
//                        "touser"=>$openid,
//                        "content"=>$content
//                    ];
//                    $MiniMsg = new  \app\common\lib\MiniMsg($msg);
//                    $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
//                }elseif($result==2){
//                    Db::startTrans();
//                    try{
//                        //删除
//                        $this->where(["order_id"=>$order_info["order_id"]]);
//                        $res = $this->delete();
//
//                        if($res){
//                            Db::name("shop_task")->where("task_id",$order_info["task_id"])->setInc("left_task_num",1);
//                            $uid = $order_info["uid"];
//                            $openid = Db::name("wx_users")->where("uid",$uid)->value("openid");
//                            $msg = [
//                                "condition"=>10,
//                                "touser"=>$openid,
//                                "content"=>["接单失败—资料未通过审核","平台管理员给予审核失败"]
//                            ];
//                            $MiniMsg = new  \app\common\lib\MiniMsg($msg);
//                            $MiniMsg->sendMsg();//发送短信模板银行卡修改成功
//                            Db::commit();
//                        }else{
//                            Db::rollback();
//                        }
//                    }catch (\Exception $e){
//                        echo $e->getMessage();exit;
//                    }
//                }
//                break;
            case 1://派客上传资料未审核的状态
                if($result==1){
                    if($order_info["task_type"]==1){
                        $this->save(["status"=>2,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);//精刷单进入已审核状态
                        Db::name("order_image")->where("order_id",$order_info["order_id"])->where("status_type",1)->update(["auth_status"=>1]);//改变图片的审核状态
                    }elseif($order_info["task_type"]==3){//订单完成

                        $this->save(["status"=>13,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);//流量单进入已完成状态
                        //发送短信模板订单完成
                        $uid = $order_info["uid"];
                        $openid = Db::name("wx_users")->where("uid",$uid)->value("openid");
                        $user_name = Db::name("user")->where("uid",$uid)->value("username");
                        $content = [
                            $order_info["shop_name"],$order_info["goods_sno"],$order_info["real_money"],$user_name
                        ];//推荐内容
                        $msg = [
                            "condition"=>14,
                            "touser"=>$openid,
                            "content"=>$content
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板订单已完成

                        //计算钱
                        $gold = new \app\common\controller\GoldBean();

                        $gold->finishedBean($order_info);

                    }elseif($order_info["task_type"]==2){
                        Db::startTrans();
                        try {
                            $res = $this->save(["status" => 2,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);//隔日单进入已审核状态可把第一次审核的资料删掉
                            //删除
                            if ($res) {
                                Db::name("order_image")->where("order_id",$order_info["order_id"])->where("status_type",1)->update(["auth_status"=>1]);
                                //缺少一个删除本地图片或者七牛图片的操作
                                Db::commit();
                            }else{

                                Db::rollback();
                            }
                        }catch (\Exception $e){
                            echo $e->getMessage();exit;
                        }
                    }
                    if($order_info["task_type"]==1){//流量单不需要

                        $join[] = ["sd_user_attribute e","e.uid = r.uid","left"];
                        $user_info = Db::name("user")->alias("r")->join($join)->where("r.uid",$order_info["uid"])->field("r.*,e.bank_name,e.bank_no,e.wx_code")->find();
                        //生成一个待支付的记录
                        $record_money_arr = [
                            "order_id"=>$order_info["order_id"],
                            "order_sno"=>$order_info["order_sno"],
                            "shop_id"=>$order_info["shop_id"],
                            "uid"=>$order_info["uid"],
                            "username"=>$user_info["username"],
                            "bank_name"=>$user_info["bank_name"],
                            "bank_no"=>$user_info["bank_no"],
                            "wx_code"=>$user_info["wx_code"],
                            "on_time"=>time(),
                            "update_time"=>time(),
                            "shop_bank_no"=>"",
                            "shop_bank_name"=>"",
                            "cash"=>$order_info["real_money"]
                        ];
                        Db::name("record_money")->insert($record_money_arr);
                    }
                }elseif($result==2){
                    Db::startTrans();
                    try{
                        $res = $this->save(["status"=>1,"update_time"=>time(),"author"=>$admin_id,"back_time"=>time()],["order_id"=>$order_info["order_id"]]);
                        if($res){
                            Db::name("order_image")->where("order_id", $order_info["order_id"])->where("status_type",1)->update(["auth_status"=>2]);
                                //删除order_image图片

                            //缺少一个删除本地图片或者七牛图片的操作
                            Db::commit();
                        }else{
                            Db::rollback();
                        }


                    }catch (\Exception $e){
                        echo $e->getMessage();exit;
                    }
                }
                break;

            case 3://派客上传资料（已上传）进行复审的时候（只有隔日单才会有已上传，复审状态）
                if($order_info["task_type"]==2) {//隔日单的审核通过的时候
                    if ($result == 1) {
                        $this->save(["status" => 4,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);
                        Db::name("order_image")->where("order_id", $order_info["order_id"])->where("status_type",2)->update(["auth_status"=>1]);

                        $join[] = ["sd_user_attribute e","e.uid = r.uid","left"];
                        $user_info = Db::name("user")->alias("r")->join($join)->where("r.uid",$order_info["uid"])->field("r.*,e.bank_name,e.bank_no,e.wx_code")->find();
                        //生成一个待支付的记录
                        $record_money_arr = [

                            "order_id"=>$order_info["order_id"],
                            "order_sno"=>$order_info["order_sno"],
                            "shop_id"=>$order_info["shop_id"],
                            "uid"=>$order_info["uid"],
                            "username"=>$user_info["username"],
                            "bank_name"=>$user_info["bank_name"],
                            "bank_no"=>$user_info["bank_no"],
                            "wx_code"=>$user_info["wx_code"],
                            "on_time"=>time(),
                            "update_time"=>time(),
                            "shop_bank_no"=>"",
                            "shop_bank_name"=>"",
                            "cash"=>$order_info["real_money"]
                        ];
                        Db::name("record_money")->insert($record_money_arr);
                    } elseif ($result == 2) {

                        Db::startTrans();
                        try {
                            $res = $this->save(["status" => 3,"update_time"=>time(),"author"=>$admin_id,"back_time"=>time()],["order_id"=>$order_info["order_id"]]);
                            if ($res) {
                                Db::name("order_image")->where("order_id", $order_info["order_id"])->where("status_type",2)->update(["auth_status"=>2]);
                                //删除order_image图片

                                //缺少一个删除本地图片或者七牛图片的操作
                                Db::commit();
                            } else {
                                Db::rollback();
                            }

                        } catch (\Exception $e) {
                            echo $e->getMessage();
                            exit;
                        }
                    }

                }
                break;
            //精刷单和隔日单流程一样（接下来通过$deliver与$praise和$review判断
            case 6://已下单审核
                if($result==1) {//审核通过
                    if ($deliver == 2 && $praise == 2) {
                        $this->save(["status" => 13,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);//隔日单和精刷单--已完成
                        //发送短信模板订单完成
                        $uid = $order_info["uid"];
                        $openid = Db::name("wx_users")->where("uid",$uid)->value("openid");
                        $user_name = Db::name("user")->where("uid",$uid)->value("username");
                        $content = [
                            $order_info["shop_name"],$order_info["goods_sno"],$order_info["real_money"],$user_name
                        ];//推荐内容
                        $msg = [
                            "condition"=>14,
                            "touser"=>$openid,
                            "content"=>$content
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板订单已完成

                        //计算钱
                        $gold = new \app\common\controller\GoldBean();

                        $gold->finishedBean($order_info);
                    }

                    if ($deliver == 2 && $praise == 1) {
                        //隔日单和精刷单--待好评
                        $this->save(["status" => 8,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);
                    }

                    if ($deliver == 1) {

                        //隔日单和精刷单--待好评
                        $this->save(["status" => 7,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);

                    }
                }elseif($result==2){//审核失败
                    Db::startTrans();
                    try {
                        //隔日单和精刷单--已付款
                        $res = $this->save(["status" => 5,"update_time"=>time(),"author"=>$admin_id,"back_time"=>time()],["order_id"=>$order_info["order_id"]]);
                        if($res) {
                            Db::name("order_image")->where(["order_id"=>$order_info["order_id"]])->update(["payed_img"=>""]);
                            Db::commit();
                        }else{
                            Db::rollback();
                        }

                    }catch (\Exception $e){
                        echo $e->getMessage();
                        exit;
                    }
                }
                break;

            case 10://已好评（待审核）
                if($result==1) {//审核通过
                    if ( $review==2 && $praise == 1) {
                        $this->save(["status" => 13,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);//隔日单和精刷单--已完成

                        //发送短信模板订单完成
                        $uid = $order_info["uid"];
                        $openid = Db::name("wx_users")->where("uid",$uid)->value("openid");
                        $user_name = Db::name("user")->where("uid",$uid)->value("username");
                        $content = [
                            $order_info["shop_name"],$order_info["goods_sno"],$order_info["real_money"],$user_name
                        ];//推荐内容
                        $msg = [
                            "condition"=>14,
                            "touser"=>$openid,
                            "content"=>$content
                        ];
                        $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                        $MiniMsg->sendMsg();//发送短信模板订单已完成


                        //计算钱
                        $gold = new \app\common\controller\GoldBean();

                        $gold->finishedBean($order_info);

                    }

                    if ($review==1 && $praise == 1) {
                        //隔日单和精刷单--待追评
                        $this->save(["status" => 11,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);
                    }
                    Db::name("praise")->where(["order_id"=>$order_info["order_id"]])->update(["auth_status"=>1]);
                }elseif($result==2){//审核失败
                    Db::startTrans();
                    try {
                        $_status = 0;
                        if($deliver==1){
                            $_status = 9;//已发货
                        }else{
                            $_status = 8;//待好评
                        }
                        //隔日单和精刷单--已发货
                        $res = $this->save(["status" => $_status,"update_time"=>time(),"author"=>$admin_id,"back_time"=>time()],["order_id"=>$order_info["order_id"]]);
                        if($res) {
                            Db::name("praise")->where(["order_id"=>$order_info["order_id"]])->update(["auth_status"=>2]);

                            //缺少删除图片操作
                            Db::commit();
                        }else{
                            Db::rollback();
                        }

                    }catch (\Exception $e){
                        echo $e->getMessage();
                        exit;
                    }
                }

                break;

            case 12://已追评（待审核）

                if($result==1) {//审核通过
                    if ( $review==1 && $praise == 1) {

                        $this->save(["status" => 13,"update_time"=>time(),"author"=>$admin_id],["order_id"=>$order_info["order_id"]]);//隔日单和精刷单--已完成
                    }

                    Db::name("review")->where(["order_id"=>$order_info["order_id"]])->update(["auth_status"=>1]);

                    //发送短信模板订单完成
                    $uid = $order_info["uid"];
                    $openid = Db::name("wx_users")->where("uid",$uid)->value("openid");
                    $user_name = Db::name("user")->where("uid",$uid)->value("username");
                    $content = [
                        $order_info["shop_name"],$order_info["goods_sno"],$order_info["real_money"],$user_name
                    ];//推荐内容
                    $msg = [
                        "condition"=>14,
                        "touser"=>$openid,
                        "content"=>$content
                    ];
                    $MiniMsg = new  \app\common\lib\MiniMsg($msg);
                    $MiniMsg->sendMsg();//发送短信模板订单已完成

                    //计算钱
                    $gold = new \app\common\controller\GoldBean();

                    $gold->finishedBean($order_info);

                }elseif($result==2){//审核失败
                    Db::startTrans();
                    try {
                        //隔日单和精刷单--待追评
                        $res = $this->save(["status" => 11,"update_time"=>time(),"author"=>$admin_id,"back_time"=>time()],["order_id"=>$order_info["order_id"]]);
                        if($res) {
                            Db::name("review")->where(["order_id"=>$order_info["order_id"]])->update(["auth_status"=>2]);

                            //缺少删除图片操作

                            Db::commit();
                        }else{
                            Db::rollback();
                        }

                    }catch (\Exception $e){
                        echo $e->getMessage();
                        exit;
                    }
                }

                break;




        }
        return true;
    }



}
